<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>房屋租赁系统</h2>
      </div>
      <div class="header-right">
        <span>欢迎您，{{ username }}</span>
      </div>
    </el-header>

    <el-container class="main-container">
      <!-- 左侧导航栏 -->
      <el-aside width="250px" class="aside">
        <!-- 用户信息卡片 -->
        <div class="user-info">
          <el-avatar :size="64" :src="userAvatar">
            <img src="/src/assets/default-avatar.png"/>
          </el-avatar>
          <h3>{{ username }}</h3>
          <el-button type="primary" size="small" @click="goToProfile">修改个人信息</el-button>
          <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
        </div>

        <el-menu
          default-active="2-4"
          class="menu"
          background-color="#304156"
          text-color="#fff"
          active-text-color="#409EFF"
          @select="handleMenuSelect"
        >
          <el-sub-menu index="1">
            <template #title>
              <el-icon><User /></el-icon>
              <span>我是租客</span>
            </template>
            <el-menu-item index="1-1">我的收藏</el-menu-item>
            <el-menu-item index="1-2">消息列表</el-menu-item>
            <el-menu-item index="1-3">我的预约</el-menu-item>
            <el-menu-item index="1-4">我的订单</el-menu-item>
            <el-menu-item index="1-5">我的租房</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>
              <el-icon><House /></el-icon>
              <span>我是房东</span>
            </template>
            <el-menu-item index="2-1">我要出租</el-menu-item>
            <el-menu-item index="2-2">消息列表</el-menu-item>
            <el-menu-item index="2-3">管理出租</el-menu-item>
            <el-menu-item index="2-4">预约反馈</el-menu-item>
            <el-menu-item index="2-5">维修反馈</el-menu-item>
            <el-menu-item index="2-6">租金收入</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main">
        <div class="appointment-feedback">
          <el-card class="main-card">
            <template #header>
              <div class="card-header">
                <span>预约反馈管理</span>
                <el-button type="primary" size="small" @click="fetchAppointments">刷新数据</el-button>
              </div>
            </template>
            
            <!-- 搜索和筛选区域 -->
            <div class="search-container">
              <el-select v-model="statusFilter" placeholder="预约状态" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="待确认" value="待确认"></el-option>
                <el-option label="已确认" value="已确认"></el-option>
                <el-option label="已取消" value="已取消"></el-option>
              </el-select>
              
              <el-button type="primary" @click="searchAppointments">搜索</el-button>
            </div>
            
            <!-- 预约列表表格 -->
            <el-table
              :data="appointmentList"
              style="width: 100%"
              border
              stripe
              v-loading="loading"
            >
              <el-table-column prop="reserve_id" label="预约ID" width="80" />
              <el-table-column prop="visitor_name" label="访客姓名" width="120" />
              <el-table-column prop="house_address" label="房屋地址" min-width="200" show-overflow-tooltip />
              <el-table-column prop="appointment_time" label="预约时间" width="180" />
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusTag(scope.row.status)">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="viewAppointmentDetails(scope.row)">查看</el-button>
                  <el-button 
                    size="small" 
                    type="primary" 
                    v-if="scope.row.status === '待确认'"
                    @click="confirmAppointment(scope.row)"
                  >
                    确认
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    v-if="scope.row.status === '待确认'"
                    @click="cancelAppointment(scope.row)"
                  >
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="appointmentDetailVisible"
      title="预约详情"
      width="600px"
    >
      <div v-if="currentAppointment" class="appointment-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="预约ID">{{ currentAppointment.reserve_id }}</el-descriptions-item>
          <el-descriptions-item label="访客姓名">{{ currentAppointment.visitor_name }}</el-descriptions-item>
          <el-descriptions-item label="房屋地址">{{ currentAppointment.house_address }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ formatDateTime(currentAppointment.appointment_time) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentAppointment.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentAppointment.status)">
              {{ currentAppointment.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="action-buttons" v-if="currentAppointment.status === '待确认'">
          <el-button type="primary" @click="confirmAppointment(currentAppointment)">确认预约</el-button>
          <el-button type="danger" @click="cancelAppointment(currentAppointment)">取消预约</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
// import { ref, onMounted } from 'vue'
// import { User, House } from '@element-plus/icons-vue'
// import { useRouter } from 'vue-router'
// import { ElMessageBox, ElMessage } from 'element-plus'
// import axios from 'axios'


// const router = useRouter()
// // 从localStorage获取用户名
// const username = ref('')
// const userAvatar = ref('')

// const loading = ref(false)
// const statusFilter = ref('')
// const currentPage = ref(1)
// const pageSize = ref(10)
// const total = ref(0)
// const appointmentList = ref([])
// const appointmentDetailVisible = ref(false)
// const currentAppointment = ref(null)

// // 获取状态标签样式
// const getStatusTag = (status) => {
//   const statusMap = {
//     '待确认': 'warning',
//     '已确认': 'success',
//     '已取消': 'danger'
//   }
//   return statusMap[status] || 'info'
// }

// // 格式化日期时间
// const formatDateTime = (dateTimeStr) => {
//   if (!dateTimeStr) return ''
//   const date = new Date(dateTimeStr)
//   return date.toLocaleString()
// }

// // 获取预约列表
// const fetchAppointments = async () => {
//   loading.value = true
//   try {
//     const response = await axios.get('http://127.0.0.1:5000/api/landlord/appointments', {
//       params: {
//         page: currentPage.value,
//         per_page: pageSize.value,
//         status: statusFilter.value
//       },
//       headers: {
//         'Authorization': `Bearer ${localStorage.getItem('token')}`
//       }
//     })
    
//     if (response.data.status === 200) {
//       appointmentList.value = response.data.data.appointments
//       total.value = response.data.data.total
//     } else {
//       ElMessage.error(response.data.msg || '获取预约列表失败')
//     }
//   } catch (error) {
//     console.error('获取预约列表失败:', error)
//     ElMessage.error('获取预约列表失败，请稍后重试')
//   } finally {
//     loading.value = false
//   }
// }

// // 搜索预约
// const searchAppointments = () => {
//   currentPage.value = 1
//   fetchAppointments()
// }

// // 查看预约详情
// const viewAppointmentDetails = (appointment) => {
//   currentAppointment.value = appointment
//   appointmentDetailVisible.value = true
// }

// // 确认预约
// const confirmAppointment = (appointment) => {
//   ElMessageBox.confirm(
//     '确定要确认该预约吗？',
//     '提示',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   ).then(async () => {
//     try {
//       const response = await axios.put(`http://127.0.0.1:5000/api/landlord/appointments/${appointment.reserve_id}/status`, {
//         status: '已确认'
//       }, {
//         headers: {
//           'Authorization': `Bearer ${localStorage.getItem('token')}`
//         }
//       })
      
//       if (response.data.status === 200) {
//         // 更新本地数据
//         const index = appointmentList.value.findIndex(a => a.reserve_id === appointment.reserve_id)
//         if (index !== -1) {
//           appointmentList.value[index].status = '已确认'
//         }
        
//         // 更新当前查看的预约
//         if (currentAppointment.value && currentAppointment.value.reserve_id === appointment.reserve_id) {
//           currentAppointment.value.status = '已确认'
//         }
        
//         ElMessage.success('预约已确认')
//       } else {
//         ElMessage.error(response.data.msg || '确认预约失败')
//       }
//     } catch (error) {
//       console.error('确认预约失败:', error)
//       ElMessage.error('确认预约失败，请稍后重试')
//     }
//   }).catch(() => {
//     // 取消操作
//   })
// }

// // 取消预约
// const cancelAppointment = (appointment) => {
//   ElMessageBox.confirm(
//     '确定要取消该预约吗？',
//     '提示',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   ).then(async () => {
//     try {
//       const response = await axios.put(`http://127.0.0.1:5000/api/landlord/appointments/${appointment.reserve_id}/status`, {
//         status: '已取消'
//       }, {
//         headers: {
//           'Authorization': `Bearer ${localStorage.getItem('token')}`
//         }
//       })
      
//       if (response.data.status === 200) {
//         // 更新本地数据
//         const index = appointmentList.value.findIndex(a => a.reserve_id === appointment.reserve_id)
//         if (index !== -1) {
//           appointmentList.value[index].status = '已取消'
//         }
        
//         // 更新当前查看的预约
//         if (currentAppointment.value && currentAppointment.value.reserve_id === appointment.reserve_id) {
//           currentAppointment.value.status = '已取消'
//         }
        
//         ElMessage.success('预约已取消')
//       } else {
//         ElMessage.error(response.data.msg || '取消预约失败')
//       }
//     } catch (error) {
//       console.error('取消预约失败:', error)
//       ElMessage.error('取消预约失败，请稍后重试')
//     }
//   }).catch(() => {
//     // 取消操作
//   })
// }

// // 处理页码变化
// const handleCurrentChange = (val) => {
//   currentPage.value = val
//   fetchAppointments()
// }

// // 处理每页显示数量变化
// const handleSizeChange = (val) => {
//   pageSize.value = val
//   currentPage.value = 1
//   fetchAppointments()
// }

// // 处理菜单选择
// const handleMenuSelect = (index) => {
//   switch(index) {
//     // 房东相关菜单
//     case '2-4': // 预约反馈
//       router.push('/landlord/appointment')
//       break
//     case '2-5': // 维修反馈
//       router.push('/landlord/maintenance')
//       break
//     case '2-6': // 租金收入
//       router.push('/landlord/income')
//       break
//     // 其他菜单项的处理...
//     default:
//       router.push('/user')
//       break
//   }
// }

// // 处理退出登录
// const handleLogout = () => {
//   ElMessageBox.confirm(
//     '确定要退出登录吗？',
//     '提示',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   ).then(() => {
//     // 清除本地存储的信息
//     localStorage.removeItem('token')
//     localStorage.removeItem('userId')
//     localStorage.removeItem('isAdmin')
//     localStorage.removeItem('username')
//     localStorage.removeItem('userAvatar')
    
//     ElMessage.success('已成功退出登录')
//     router.push('/login')
//   }).catch(() => {
//     // 取消退出登录
//   })
// }

// // 打开个人信息修改弹窗
// const goToProfile = () => {
//   router.push('/user')
// }

// onMounted(() => {
//   // 获取登录时存储的用户信息
//   username.value = localStorage.getItem('username') || '用户'
//   userAvatar.value = localStorage.getItem('userAvatar') || ''
//   fetchAppointments()
// })
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import request from '../../utils/request'
 // 使用你写好的封装axios实例

const router = useRouter()

// 从localStorage获取用户名和头像
const username = ref(localStorage.getItem('username') || '用户')
const userAvatar = ref(localStorage.getItem('userAvatar') || '')

const loading = ref(false)
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const appointmentList = ref([])
const appointmentDetailVisible = ref(false)
const currentAppointment = ref(null)

// 状态标签样式映射
const getStatusTag = (status) => {
  const statusMap = {
    '待确认': 'warning',
    '已确认': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString()
}

// const fetchAppointments = async () => {
//   loading.value = true
//   try {
//     const res = await request.get('/landlord/appointments', {
//       params: {
//         page: currentPage.value,
//         per_page: pageSize.value,
//         status: statusFilter.value
//       }
//     })

//     // 因为已经是 response.data，判断 code 而不是 status
//     if (res.code === 200) {
//       appointmentList.value = res.data.appointments
//       total.value = res.data.total
//     } else {
//       ElMessage.error(res.msg || '获取预约列表失败')
//     }

//   } catch (error) {
//     console.error('获取预约列表失败:', error)
//     ElMessage.error('获取预约列表失败，请稍后重试')
//   } finally {
//     loading.value = false
//   }
// }
const fetchAppointments = async () => {
  loading.value = true
  try {
    console.log('获取预约列表，当前token:', localStorage.getItem('token'))
    const res = await request.get('/api/landlord/appointments', {
      params: {
        page: currentPage.value,
        per_page: pageSize.value,
        status: statusFilter.value
      }
    })

    console.log('预约列表响应:', res)
    // 兼容处理，检查status或code字段
    if (res.status === 200 || res.code === 200) {
      appointmentList.value = res.data.appointments
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      // 清除本地存储的信息
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('isAdmin')
      localStorage.removeItem('username')
      localStorage.removeItem('userAvatar')
      
      router.push('/login')
    } else {
      ElMessage.error('获取预约列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 搜索预约
const searchAppointments = () => {
  currentPage.value = 1
  fetchAppointments()
}

// 查看预约详情
const viewAppointmentDetails = (appointment) => {
  currentAppointment.value = appointment
  appointmentDetailVisible.value = true
}

// 确认预约
const confirmAppointment = (appointment) => {
  ElMessageBox.confirm(
    '确定要确认该预约吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await request.put(`/api/landlord/appointments/${appointment.reserve_id}/status`, {
        status: '已确认'
      })

      if (response.status === 200) {
        const index = appointmentList.value.findIndex(a => a.reserve_id === appointment.reserve_id)
        if (index !== -1) {
          appointmentList.value[index].status = '已确认'
        }
        if (currentAppointment.value && currentAppointment.value.reserve_id === appointment.reserve_id) {
          currentAppointment.value.status = '已确认'
        }
        ElMessage.success('预约已确认')
      } else {
        ElMessage.error(response.msg || '确认预约失败')
      }
    } catch (error) {
      console.error('确认预约失败:', error)
      ElMessage.error('确认预约失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 取消预约
const cancelAppointment = (appointment) => {
  ElMessageBox.confirm(
    '确定要取消该预约吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await request.put(`/api/landlord/appointments/${appointment.reserve_id}/status`, {
        status: '已取消'
      })

      if (response.status === 200) {
        const index = appointmentList.value.findIndex(a => a.reserve_id === appointment.reserve_id)
        if (index !== -1) {
          appointmentList.value[index].status = '已取消'
        }
        if (currentAppointment.value && currentAppointment.value.reserve_id === appointment.reserve_id) {
          currentAppointment.value.status = '已取消'
        }
        ElMessage.success('预约已取消')
      } else {
        ElMessage.error(response.msg || '取消预约失败')
      }
    } catch (error) {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 处理分页页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppointments()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchAppointments()
}

// 菜单选择跳转
const handleMenuSelect = (index) => {
  switch(index) {
    case '2-4': // 预约反馈
      router.push('/landlord/appointment')
      break
    case '2-5': // 维修反馈
      router.push('/landlord/maintenance')
      break
    case '2-6': // 租金收入
      router.push('/landlord/income')
      break
    default:
      router.push('/user')
      break
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    localStorage.clear() // 清理所有本地存储
    ElMessage.success('已成功退出登录')
    router.push('/login')
  }).catch(() => {
    // 取消退出
  })
}

// 个人信息页跳转
const goToProfile = () => {
  router.push('/user')
}

onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  background-color: #f0f2f5;
}

.header {
  background-color: #409EFF; /* 修改背景颜色为蓝色 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header-left h2 {
  color: #fff; /* 修改文字颜色为白色 */
  margin: 0;
}

.header-right span {
  color: #fff; /* 修改文字颜色为白色 */
}

.main-container {
  height: calc(100vh - 60px);
}

.aside {
  background-color: #304156;
  height: 100%;
}

.menu {
  border-right: none;
}

.user-info {
  padding: 20px;
  text-align: center;
  background-color: #263445;
  color: #fff;
}

.user-info h3 {
  margin: 10px 0;
  font-size: 16px;
  color: #fff;
}

.user-info .el-button {
  margin-top: 10px;
}

.main {
  padding: 20px;
  background-color: #f0f2f5;
  overflow-y: auto;
}

.appointment-feedback {
  width: 100%;
}

.main-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.appointment-detail {
  padding: 10px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>